//
//  ByUIRealTimeVC.m
//  laserdevice_ios
//
//  Created by pro on 16/11/25.
//  Copyright © 2016年 com.itboye. All rights reserved.
//

#import "ByUIRealTimeVC.h"

// 手机震动
#import <AudioToolbox/AudioToolbox.h>


// 蓝牙
#import "ByBlueToothHandleModel.h"                                //
#import "ByBlueToothDataOperationModel.h"

// view
#import "ByUIRealTimeAlertTypeSelectView.h"                       // 提醒类型选择视图

#import "ByChartBaseView.h"                                       // 图标

// vc
#import "ByUIRealTimeHistoryVC.h"     

#import "ByAudioServices.h"

@interface ByUIRealTimeVC ()

// view
@property (nonatomic, strong) UIScrollView    *scroll;            // 滑动视图，用于适配
@property (nonatomic, strong) ByChartBaseView *chart;             // 表格

@property (nonatomic, strong) UITextField     *limitMinTf;        // 距离上限
@property (nonatomic, strong) UITextField     *limitMaxTf;        // 距离下限
@property (nonatomic, strong) UITextField     *usefulMinTf;       // 距离区间，小
@property (nonatomic, strong) UITextField     *usefulMaxTf;       // 距离区间，大
@property (nonatomic, strong) UITextField     *alertMaxTimeTf;    // 提醒最大时间

// data
@property (nonatomic, strong) NSMutableArray  *dataArray;         // 数据数组
@property (nonatomic, strong) NSMutableString *dataString;        // 数据字符串

@property (nonatomic, assign) int alertType;


@end

@implementation ByUIRealTimeVC
{
    CGFloat _noDataTime;  // 没收到数据的时间
    
    NSTimer *_timer;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = STRING(@"shishiceju");
    self.tintColor = [UIColor whiteColor];

    [self addLeftBackBarButtonItem];
    [self addBYItemviews:@[STRING(@"lishishuju")] mode:ByNavigationItemModeImageAndText position:ByNavigationItemPositionModeRight];
    
    
    [self createChartView];
    [self createLabelAndTextfield];
    
    // 初始化存储数据
    self.alertType = 0;
    self.dataArray = [[NSMutableArray alloc] init];
    self.dataString = [[NSMutableString alloc] init];

    // 开启定时器
    _noDataTime = 0.0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector (timerAction:) userInfo:nil repeats:YES];

}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if ([ByBlueToothHandleModel shareInstance].characteristic) {
        [[ByBlueToothHandleModel shareInstance] closeRealTimeMeasure];
    }
    
    [_timer invalidate];
    _timer = nil;
}

#pragma mark - create views
- (UIScrollView *)scroll {
    
    if (!_scroll) {
        _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        _scroll.backgroundColor = rgba(4, 31, 60, 1);
        _scroll.showsVerticalScrollIndicator = NO;
        _scroll.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_scroll];
    }
    return _scroll;
}
// 表格
- (void)createChartView {
    
    self.chart = [[ByChartBaseView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.scroll.height * 0.5 + 40)];
    [self.scroll addSubview:self.chart];
}
- (void)createLabelAndTextfield {
    
    CGFloat x, y, width, height;
    NSString *text = @"";
    
    // 单位
    NSMutableArray *unitLabels = [[NSMutableArray alloc] init];
    for (int i = 0; i < 5; i ++) {
        x = 0;
        y = 0;
        width = 30;
        height = 15;
        UILabel *unitLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
        unitLabel.adjustsFontSizeToFitWidth = YES;
        unitLabel.font = FONT(14);
        int unit = [ByCommonCache getSystemUnit].intValue;
        switch (unit) {
            case 0: // 米
                unitLabel.text = @"m";
                break;
            case 1: // 英尺
                unitLabel.text = @"ft";
                break;
            case 2: // 英寸
                unitLabel.text = @"in";
                break;
            case 3: // 英尺+英寸
                unitLabel.text = @"ft";
                break;
            default:
                break;
        }
        if (i == 4) {
            unitLabel.text = @"s";
        }
        unitLabel.textColor = [UIColor whiteColor];
        unitLabel.textAlignment = NSTextAlignmentCenter;
        unitLabel.width = [unitLabel.text getSizeOfString:14].width + 5;
        
        [unitLabels addObject:unitLabel];
    }
    
    
    // 1.设置距离提示阀值
    text = STRING(@"julifazhi");
    x = 10;
    y = self.chart.bottom + 10;
    width = self.scroll.width - 2 * x;
    height = 20;
    UILabel *setTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    setTitleLabel.adjustsFontSizeToFitWidth = YES;
    setTitleLabel.font = FONT(15);
    setTitleLabel.text = text;
    setTitleLabel.textColor = [UIColor whiteColor];
    setTitleLabel.textAlignment = NSTextAlignmentLeft;
    [self.scroll addSubview:setTitleLabel];
    
    // 2.设置距离上限
    text = STRING(@"julishangxian");
    x = 10;
    y = setTitleLabel.bottom + 10;
    width = [text getSizeOfString:14].width + 5;
    height = 20;
    UILabel *limitMaxTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    limitMaxTitleLabel.adjustsFontSizeToFitWidth = YES;
    limitMaxTitleLabel.font = FONT(14);
    limitMaxTitleLabel.text = text;
    limitMaxTitleLabel.textColor = [UIColor whiteColor];
    limitMaxTitleLabel.textAlignment = NSTextAlignmentLeft;
    [self.scroll addSubview:limitMaxTitleLabel];
    
    // 3.距离上限的输入框
    x = limitMaxTitleLabel.right;
    y = limitMaxTitleLabel.top;
    width = self.scroll.width / 2 - 10 - x;
    height = 20;
    self.limitMaxTf = [[UITextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
    self.limitMaxTf.keyboardType = UIKeyboardTypeDecimalPad;
    self.limitMaxTf.font = FONT(14);
    self.limitMaxTf.textAlignment = NSTextAlignmentCenter;
    self.limitMaxTf.textColor = [UIColor whiteColor];
    [self.scroll addSubview:self.limitMaxTf];
    self.limitMaxTf.layer.borderColor = [UIColor whiteColor].CGColor;
    self.limitMaxTf.layer.borderWidth = 1;
    self.limitMaxTf.rightViewMode = UITextFieldViewModeAlways;
    self.limitMaxTf.rightView = unitLabels[0];
    
    
    // 4.设置距离下限
    text = STRING(@"julixiaxian");
    x = self.scroll.width / 2 + 10;
    y = setTitleLabel.bottom + 10;
    width = [text getSizeOfString:14].width + 5;
    height = 20;
    UILabel *limitMinTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    limitMinTitleLabel.adjustsFontSizeToFitWidth = YES;
    limitMinTitleLabel.font = FONT(14);
    limitMinTitleLabel.text = text;
    limitMinTitleLabel.textColor = [UIColor whiteColor];
    limitMinTitleLabel.textAlignment = NSTextAlignmentLeft;
    [self.scroll addSubview:limitMinTitleLabel];
    
    // 5.距离上限的输入框
    x = limitMinTitleLabel.right;
    y = limitMinTitleLabel.top;
    width = self.scroll.width - 10 - x;
    height = 20;
    self.limitMinTf = [[UITextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
    self.limitMinTf.keyboardType = UIKeyboardTypeDecimalPad;
    self.limitMinTf.font = FONT(14);
    self.limitMinTf.textAlignment = NSTextAlignmentCenter;
    self.limitMinTf.textColor = [UIColor whiteColor];
    [self.scroll addSubview:self.limitMinTf];
    self.limitMinTf.layer.borderColor = [UIColor whiteColor].CGColor;
    self.limitMinTf.layer.borderWidth = 1;
    self.limitMinTf.rightViewMode = UITextFieldViewModeAlways;
    self.limitMinTf.rightView = unitLabels[1];

    
    // 6.设置距离区间
    text = STRING(@"juliqujian");
    x = 10;
    y = limitMinTitleLabel.bottom + 10;
    width = [text getSizeOfString:14].width + 5;
    height = 20;
    UILabel *usefulTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    usefulTitleLabel.adjustsFontSizeToFitWidth = YES;
    usefulTitleLabel.font = FONT(14);
    usefulTitleLabel.text = text;
    usefulTitleLabel.textColor = [UIColor whiteColor];
    usefulTitleLabel.textAlignment = NSTextAlignmentLeft;
    [self.scroll addSubview:usefulTitleLabel];
    
    // 7.距离区间（小）的输入框
    x = usefulTitleLabel.right;
    y = usefulTitleLabel.top;
    width = self.limitMinTf.width;
    height = 20;
    self.usefulMinTf = [[UITextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
    self.usefulMinTf.keyboardType = UIKeyboardTypeDecimalPad;
    self.usefulMinTf.font = FONT(14);
    self.usefulMinTf.textAlignment = NSTextAlignmentCenter;
    self.usefulMinTf.textColor = [UIColor whiteColor];
    [self.scroll addSubview:self.usefulMinTf];
    self.usefulMinTf.layer.borderColor = [UIColor whiteColor].CGColor;
    self.usefulMinTf.layer.borderWidth = 1;
    self.usefulMinTf.rightViewMode = UITextFieldViewModeAlways;
    self.usefulMinTf.rightView = unitLabels[2];

    // 8.横线
    x = self.usefulMinTf.right + 5;
    y = 0;
    width = 15;
    height = 1;
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    line.backgroundColor = [UIColor whiteColor];
    [self.scroll addSubview:line];
    line.y = self.usefulMinTf.y;
    
    // 9.距离区间（大）的输入框
    x = line.right + 5;
    y = usefulTitleLabel.top;
    width = self.usefulMinTf.width;
    height = 20;
    self.usefulMaxTf = [[UITextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
    self.usefulMaxTf.keyboardType = UIKeyboardTypeDecimalPad;
    self.usefulMaxTf.font = FONT(14);
    self.usefulMaxTf.textAlignment = NSTextAlignmentCenter;
    self.usefulMaxTf.textColor = [UIColor whiteColor];
    [self.scroll addSubview:self.usefulMaxTf];
    self.usefulMaxTf.layer.borderColor = [UIColor whiteColor].CGColor;
    self.usefulMaxTf.layer.borderWidth = 1;
    self.usefulMaxTf.rightViewMode = UITextFieldViewModeAlways;
    self.usefulMaxTf.rightView = unitLabels[3];

    // 10.设置提示最大时间阀值
    text = STRING(@"shijianfazhi");
    x = 10;
    y = usefulTitleLabel.bottom + 10;
    width = [text getSizeOfString:14].width + 5;
    height = 20;
    UILabel *alertMaxTimeTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    alertMaxTimeTitleLabel.adjustsFontSizeToFitWidth = YES;
    alertMaxTimeTitleLabel.font = FONT(14);
    alertMaxTimeTitleLabel.text = text;
    alertMaxTimeTitleLabel.textColor = [UIColor whiteColor];
    alertMaxTimeTitleLabel.textAlignment = NSTextAlignmentLeft;
    [self.scroll addSubview:alertMaxTimeTitleLabel];
    
    // 11.提醒最大时间的输入框
    x = alertMaxTimeTitleLabel.right;
    y = alertMaxTimeTitleLabel.top;
    width = self.usefulMaxTf.width;
    height = 20;
    self.alertMaxTimeTf = [[UITextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
    self.alertMaxTimeTf.keyboardType = UIKeyboardTypeDecimalPad ;
    self.alertMaxTimeTf.font = FONT(14);
    self.alertMaxTimeTf.textAlignment = NSTextAlignmentCenter;
    self.alertMaxTimeTf.textColor = [UIColor whiteColor];
    [self.scroll addSubview:self.alertMaxTimeTf];
    self.alertMaxTimeTf.layer.borderColor = [UIColor whiteColor].CGColor;
    self.alertMaxTimeTf.layer.borderWidth = 1;
    self.alertMaxTimeTf.rightViewMode = UITextFieldViewModeAlways;
    self.alertMaxTimeTf.rightView = unitLabels[4];

    
    // 12.设置提醒种类
    text = STRING(@"tixingzhonglei");
    x = 10;
    y = alertMaxTimeTitleLabel.bottom + 10;
    width = [text getSizeOfString:14].width + 5;
    height = 20;
    UILabel *alertTypeTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    alertTypeTitleLabel.adjustsFontSizeToFitWidth = YES;
    alertTypeTitleLabel.font = FONT(14);
    alertTypeTitleLabel.text = text;
    alertTypeTitleLabel.textColor = [UIColor whiteColor];
    alertTypeTitleLabel.textAlignment = NSTextAlignmentLeft;
    [self.scroll addSubview:alertTypeTitleLabel];
    
    // 13.种类选择视图
    x = 10;
    y = alertTypeTitleLabel.bottom + 10;
    width = self.view.width - x * 2;
    height = 30;
    ByUIRealTimeAlertTypeSelectView *typeView = [[ByUIRealTimeAlertTypeSelectView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [typeView setSelectedAction:^(NSInteger index) {
        self.alertType = (int)index;
        [self alert];
    }];
    [self.scroll addSubview:typeView];
    
    // 14.新建按钮
    CGFloat margin = 3;
    x = 10;
    y = typeView.bottom + 10;
    width = (self.view.width - x * 2 - 10 * 2) / 3;
    height = 30;
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.frame = CGRectMake(x, y, width, height);
    newButton.backgroundColor = CJ_THEME_COLOR;
    newButton.titleLabel.font = FONT(15);
    newButton.layer.cornerRadius = 4;
    [newButton setTitle:STRING(@"xinjian") forState:UIControlStateNormal];
    [newButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [newButton setImage:[UIImage imageNamed:@"real-time_xinjian"] forState:UIControlStateNormal];
    [newButton setTitleEdgeInsets:UIEdgeInsetsMake(0, margin, 0, -margin)];
    [newButton setImageEdgeInsets:UIEdgeInsetsMake(0, -margin, 0, margin)];
    [newButton addTarget:self action:@selector(newBuild) forControlEvents:UIControlEventTouchUpInside];
    [self.scroll addSubview:newButton];
    
    // 15.开始按钮
    x = newButton.right + 10;
    y = typeView.bottom + 10;
    width = newButton.width;
    height = 30;
    UIButton *beginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    beginButton.frame = CGRectMake(x, y, width, height);
    beginButton.backgroundColor = CJ_THEME_COLOR;
    beginButton.titleLabel.font = FONT(15);
    beginButton.layer.cornerRadius = 4;
    [beginButton setTitle:STRING(@"kaishi") forState:UIControlStateNormal];
    [beginButton setTitle:STRING(@"jieshu") forState:UIControlStateSelected];
    [beginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [beginButton setImage:[UIImage imageNamed:@"real-time_kaishi"] forState:UIControlStateNormal];
    [beginButton setImage:[UIImage imageNamed:@"real-time_jieshu"] forState:UIControlStateSelected];
    [beginButton setTitleEdgeInsets:UIEdgeInsetsMake(0, margin, 0, -margin)];
    [beginButton setImageEdgeInsets:UIEdgeInsetsMake(0, -margin, 0, margin)];
    [beginButton addTarget:self action:@selector(begin:) forControlEvents:UIControlEventTouchUpInside];
    [self.scroll addSubview:beginButton];
    beginButton.tag = 100;
    
    // 16.保存按钮
    x = beginButton.right + 10;
    y = typeView.bottom + 10;
    width = beginButton.width;
    height = 30;
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    saveButton.frame = CGRectMake(x, y, width, height);
    saveButton.backgroundColor = CJ_THEME_COLOR;
    saveButton.titleLabel.font = FONT(15);
    saveButton.layer.cornerRadius = 4;
    [saveButton setTitle:STRING(@"baocun") forState:UIControlStateNormal];
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveButton setImage:[UIImage imageNamed:@"real-time_baocun"] forState:UIControlStateNormal];
    [saveButton setTitleEdgeInsets:UIEdgeInsetsMake(0, margin, 0, -margin)];
    [saveButton setImageEdgeInsets:UIEdgeInsetsMake(0, -margin, 0, margin)];
    [saveButton addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    [self.scroll addSubview:saveButton];
    
    // 15.适配滑动
    if (self.scroll.height < saveButton.bottom + 10) {
        self.scroll.contentSize = CGSizeMake(0, saveButton.bottom + 10);
    }
}
- (void)newBuild {
    
    [UIAlertView showWithTitle:STRING(@"xinjiantubiao") message:STRING(@"xinjiantubiao-jinggao") cancelButtonTitle:STRING(@"quxiao") otherButtonTitles:@[STRING(@"xinjian")] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
    
        if (buttonIndex == 1) {
            // 先关闭实时测量
            [[ByBlueToothHandleModel shareInstance] closeRealTimeMeasure];
            
            // 改变按钮的选中状态（变为开始）
            UIButton *beginButton = (UIButton *)[self.scroll viewWithTag:100];
            beginButton.selected = NO;
            
            // 重新创建一个折线视图
            [self.chart removeFromSuperview];
            self.chart = nil;
            self.chart = [[ByChartBaseView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.scroll.height * 0.5 + 40)];
            [self.scroll addSubview:self.chart];
            
            // 重置数据
            [self.dataArray removeAllObjects];
        }
    }];
    
}
- (void)begin:(UIButton *)sender {
    
    sender.selected = !sender.selected;

    if (sender.selected) {
        
        if (![ByBlueToothHandleModel shareInstance].characteristic) {
            [ByCoreToolAlert showFailureWithText:STRING(@"qinglianjielanya")];
            return;
        }
        
        if (_timer == nil) {
            _noDataTime = 0.0;
            _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector (timerAction:) userInfo:nil repeats:YES];
        }
        [[ByBlueToothHandleModel shareInstance] startRealTimeMeasure:^(NSString *dataHex) {
            
            NSLog(@"我的数据:%@", dataHex);

            // 接收到应答信号则不做处理
            if ([dataHex isEqualToString:@"F0"] || [dataHex isEqualToString:@"f0"]) {
                return;
            }
         
            [self.dataString appendString:dataHex];
            // 接收到以FA为后缀的，说明数据接收完成
            if ([self.dataString hasSuffix:@"FA"] || [self.dataString hasSuffix:@"fa"]) {
                
                [_timer fire];
                // 收到数据后，重置时间
                _noDataTime = 0;
                
                
                // 实用数据
                NSNumber *dataNumber = [ByBlueToothDataOperationModel real_timeMeasureDataOperation:self.dataString];
                
                
                // 数据可用，则添加到数据字典
                if (dataNumber) {
                    [self.dataArray addObject:dataNumber];
                    
                    // 提醒
                    [self isShouldAlert:dataNumber];
                }
                
                // 把可变数据字符串清空
                self.dataString = [[NSMutableString alloc] init];
                
                // 重绘折线图
                self.chart.totalMeasureValues = [self.dataArray copy];
            }
            
        }];
    } else {
        NSLog(@"关闭实时测量");
        [_timer invalidate];
        _timer = nil;

        if ([ByBlueToothHandleModel shareInstance].characteristic) {
            [[ByBlueToothHandleModel shareInstance] closeRealTimeMeasure];
        }
        
    }
    
}


#pragma mark - 点击事件
- (void)leftItemsAction:(NSInteger)leftIndex {
    
    
    [UIAlertView showWithTitle:STRING(@"tuichu") message:STRING(@"tuichuqianshifoubaocun") cancelButtonTitle:STRING(@"zhijietuichu") otherButtonTitles:@[STRING(@"xianbaocun")] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [super leftItemsAction:leftIndex];
            return;
        } else {
            [self performSelector:@selector(save:) withObject:nil afterDelay:0.5];
        }
    }];
    
    
}

- (void)save:(UIButton *)sender {
    
    CGSize size = self.chart.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [self.chart.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    [UIAlertView showWithTitle:nil
                       message:STRING(@"weiceliangshujumingming")
                         style:UIAlertViewStylePlainTextInput
                   defaultText:[NSDate getCurrentDateForStringFormatWithFormatter:nil]
             cancelButtonTitle:STRING(@"quxiao")
             otherButtonTitles:@[STRING(@"queding")]
                      tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        UITextField *tf = [alertView textFieldAtIndex:0];
        if (buttonIndex == 1) {
            
            NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] init];
            [tempDic setObject:tf.text forKey:@"name"];
            [tempDic setObject:@"PDF" forKey:@"source_type"];
            [tempDic setObject:[NSDate getCurrentDateForStringFormatWithFormatter:nil] forKey:@"create_time"];
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tempDic.copy options:NSJSONWritingPrettyPrinted error:nil];
            
            [ByFileManager saveMeastureForPDFWithName:tf.text
                                                image:image
                                                 size:CGSizeMake(self.chart.width, self.chart.height)
                                                 json:jsonData];

            if (sender == nil) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
    }];

}

- (void)rightItemsAction:(NSInteger)rightIndex {
    
    ByUIRealTimeHistoryVC *vc = [[ByUIRealTimeHistoryVC alloc] init];
    [self by_normalPush:vc hasNavi:YES];
}


- (void)timerAction:(NSTimer *)timer {
    
    _noDataTime += 1;
    
    CGFloat timeMax = _alertMaxTimeTf.text.length > 0 ? _alertMaxTimeTf.text.floatValue : HUGE_VALF;

    if (_noDataTime > timeMax) {
        
//        _noDataTime = 0;
        [self alert];
    }
}

- (void)isShouldAlert:(NSNumber *)dataNumber {
    
    CGFloat limitMax = _limitMaxTf.text.length > 0 ? _limitMaxTf.text.floatValue : HUGE_VALF;
    CGFloat limitMin = _limitMinTf.text.length > 0 ? _limitMinTf.text.floatValue : -1;
    CGFloat usefulMax = _usefulMaxTf.text.length > 0 ? _usefulMaxTf.text.floatValue : 0;
    CGFloat usefulMin = _usefulMinTf.text.length > 0 ? _usefulMinTf.text.floatValue : 0;
    if (usefulMax < usefulMin) {
        CGFloat temp = usefulMax;
        usefulMax = usefulMin;
        usefulMin = temp;
    }

    int unit = [ByCommonCache getSystemUnit].intValue;
    CGFloat number = dataNumber.floatValue;
    switch (unit) {
        case 0: // 米
            number = number;
            break;
        case 1: // 英尺
            number *= 3.2808399;
            break;
        case 2: // 英寸
            number *= (3.2808399 * 12);
            break;
        case 3: // 英尺+英寸
            number *= 3.2808399;
            break;
        default:
            break;
    }
    
    if (number <= limitMin || number >= limitMax || (number <= usefulMax && number >= usefulMin)) {
        [self alert];
    }
}

- (void)alert {
   

    
    int index = self.alertType;
    if (index == 0) {
        
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
    if (index == 1) {
        SystemSoundID soundID = 1007;
        AudioServicesPlaySystemSound(soundID);
    }
    if (index == 2) {
        SystemSoundID soundID = 1007;
        AudioServicesPlaySystemSound(soundID);
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

    }
}


@end
